package odgs;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

import odgs.app.GridServer;
import odgs.listener.AcceptorListener;

public class Acceptor implements Runnable
{
	public static final int PC = 0;
	public static final int PDA = 1;
	private ServerSocket serverSocket;
	private List<AcceptorListener> acceptorListeners = new ArrayList<AcceptorListener>();
	private int myPort;
	private int mode;
	
	public Acceptor(int port, int mode) throws IOException
	{
		serverSocket = new ServerSocket(port);
		myPort = port;
		this.mode = mode;
	}
	
	public void addAcceptorListener(AcceptorListener listener)
	{
		acceptorListeners.add(listener);
	}

	public void run()
	{
		while(true)
		{
			try
			{
				Socket socket = serverSocket.accept();
				
				if(mode == PDA)
				{
					notifyPdaAcceptEvent(socket);
				}
				
				else
				{
					notifyAcceptEvent(socket);
				}
			} 
			catch (IOException e)
			{
				e.printStackTrace();
			}
		}
	}

	private void notifyPdaAcceptEvent(Socket socket) {
		for(AcceptorListener listener : acceptorListeners)
		{
			listener.pdaAccepted(socket);
		}
	}

	private void notifyAcceptEvent(Socket socket)
	{
		for(AcceptorListener listener : acceptorListeners)
		{
			listener.accepted(socket);
		}
	}

	public int getPort() {
		return myPort;
	}
}